<template>
  <div class="articleList" ref="artList">
    <van-pull-refresh v-model="pullLoading" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <van-cell
          v-for="item in list"
          :key="item.art_id"
          :title="item.title"
          @click="
            $router.push({ path: '/article', query: { id: item.art_id } })
          "
        >
          <template #label>
            <van-grid :border="false" :column-num="item.cover.type">
              <van-grid-item
                v-for="(value, index) in item.cover.images"
                :key="index"
              >
                <van-image :src="value" />
              </van-grid-item>
            </van-grid>
            <span>{{ item.aut_name }}</span>
            <span class="comment">{{ item.comm_count }}条评论</span>
            <span>{{ item.pubdate | relvTime }}</span>
            <van-icon name="cross" class="crossName" />
          </template>
        </van-cell>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { articleListAPI } from '@/api'
export default {
  name: 'articleList',
  props: {
    channel_id: {
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      pullLoading: false,
      // 保存滚动条距离
      scrollTop: 0
    }
  },
  methods: {
    async onLoad () {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const res = await articleListAPI({
        channel_id: this.channel_id,
        timestamp: this.timestamp
      })
      //   console.log(res)
      // 拿到数据后保存到数组里不断增多
      this.list.push(...res.data.data.results)
      this.timestamp = res.data.data.pre_timestamp
      // 加载状态结束
      this.loading = false

      // 当数据返回为null时代表已经加载完成了，这时候我们需要停止加载
      if (this.timestamp == null) {
        this.finished = true
      }
    },
    // 下拉刷新数据

    async onRefresh () {
      const res = await articleListAPI({
        channel_id: this.channel_id,
        timestamp: Date.now()
      })
      this.list = res.data.data.results
      this.timestamp = res.data.data.pre_timestamp
      // 关闭下拉加载状态
      this.pullLoading = false
    }
  },
  mounted () {
    // 给dom盒子加滚动事件
    this.$refs.artList.onscroll = () => {
      this.scrollTop = this.$refs.artList.scrollTop
    }
  },
  activated () {
    // 激活时再把之前的滚动条的高度赋值给滚动条，让它滚到对应的位置
    this.$refs.artList.scrollTop = this.scrollTop
  }
}
</script>

<style lang="less" scoped>
.articleList {
  width: 100%;
  position: fixed;
  top: 90px;
  bottom: 50px;
  left: 0;
  overflow: scroll;
  .comment {
    margin: 0 15px;
  }
  .crossName {
    float: right;
  }
}
</style>
